<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\common\model;

use think\Model;

class RecordBrokerage extends Model
{
    protected $dateFormat = 'Y-m-d H:i:s';
    protected $type = [
        'vote_time'  =>  'timestamp',
        'share_time'  =>  'timestamp',
    ];

    // 佣金记录（投票与分享添加）
    public function allot($brokerage, $brokerageAmount, $data, $is_vote = 1)
    {
        $data['amount'] = $brokerageAmount;
        $voteAmount = $brokerageAmount * $brokerage->vote_ratio / ($brokerage->share_ratio + $brokerage->vote_ratio);
        $data['vote_amount'] = round($voteAmount, 2);
        $data['share_amount'] = $brokerageAmount - $data['vote_amount'];
        $data['create_time'] = time();
        $is_vote ? $data['vote_time'] = time() : $data['share_time'] = time();
        if($this->insert($data)) {
            return [
                'vote_amount' => $data['vote_amount'],
                'share_amount' => $data['share_amount'],
            ];
        } else {
            return false;
        }
    }

    // 获取我投票的(获取佣金)
    public static function oneForAll($map)
    {
        $list = self::alias('r')->join('apply a', 'r.apply_id = a.id')
            ->where($map)
            ->field('r.user_id, r.apply_id, r.vote_amount, r.vote_time, r.share_amount, r.share_time, a.baby_name')
            ->select();
        $amount = 0;
        foreach($list as $key => $val) {
            if(strtotime($val['vote_time'])) $amount += $val['vote_amount'];
            if(strtotime($val['share_time'])) $amount += $val['share_amount'];
        }
        return [
            'amount' => $amount,
            'list' => $list
        ];
    }

    // 获取投票给我的（支付佣金）
    public static function allForOne($map)
    {
        $list = self::alias('r')->join('user u', 'u.id = r.user_id')
            ->where($map)
            ->field('r.user_id, r.apply_id, r.vote_amount, r.vote_time, r.share_amount, r.share_time, u.nickname')
            ->select();
        $amount = 0;
        foreach($list as $key => $val) {
            if($val['vote_time']) $amount += $val['vote_amount'];
            if($val['share_time']) $amount += $val['share_amount'];
        }
        return [
            'amount' => $amount,
            'list' => $list
        ];
    }
}
